package com.bawei.login.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.common.viewmodel.BaseViewModel
import com.bawei.login.intent.LoginViewIntent
import com.bawei.login.model.LoginRepository
import com.bawei.login.uistate.LoginUiState
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.JsonUtils
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2024/5/25
 * Desc:登录模块ViewModel
 */

@HiltViewModel
class LoginViewModel @Inject constructor(private val repository: LoginRepository) : BaseViewModel<LoginViewIntent>(){

    private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.NoneState)
    val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: LoginViewIntent) {
        when(intent){
            is LoginViewIntent.LoginToServer -> loginToServer(intent.name, intent.pwd)
            is LoginViewIntent.RegisterToServer -> registerToServer(intent.name, intent.pwd)
            else -> {}
        }

    }
    private fun loginToServer(name: String, pwd: String){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                //封装参数
                var mapParams = mutableMapOf("uName" to name, "uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis() / 1000).toString()
                var json = GsonUtils.toJson(mapParams).toString()
                var paramsBody = json.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
                //调用接口返回数据
                var resultData = repository.loginToServer(paramsBody)
                if (resultData.statuesCode == "200"){
                    MMKV.defaultMMKV().encode("token", resultData.getValues().token)
                    MMKV.defaultMMKV().encode("main_url", resultData.home)
                    MMKV.defaultMMKV().encode("userId", resultData.getValues().uId)
                    _uiState.value = LoginUiState.LoginSuccess(resultData.getValues())
                } else {
                    _uiState.value = LoginUiState.LoginFail(resultData.msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.value = LoginUiState.LoginFail(e.message ?: "接口异常，请联系客服！")
            } finally {
                cancel()
            }
        }
    }

    private fun registerToServer(name: String, pwd: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {//封装参数
                var mapParams = mutableMapOf("uName" to name, "uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis() / 1000).toString()
                var json = GsonUtils.toJson(mapParams).toString()
                var paramsBody = json.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
                //调用接口返回数据
                var resultData = repository.registerToServer(paramsBody)
                if (resultData.statuesCode == "200"){
                    _uiState.value = LoginUiState.RegisterSuccess(resultData.getValues())
                } else {
                    _uiState.value = LoginUiState.RegisterFail(resultData.msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.value = LoginUiState.LoginFail(e.message ?: "接口异常，请联系客服！")
            } finally {
                cancel()
            }
        }
    }






}